package com.slipper.ai.flow.support;

import com.slipper.ai.flow.INodeDealer;
import com.slipper.ai.flow.vo.*;
import com.slipper.groovy.service.GroovyService;
import com.slipper.util.Tool;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component("aiScriptNodeDealer")
public class ScriptNodeDealer implements INodeDealer {
    @Override
    public String getType() {
        return NodeVO.TYPE_SCRIPT;
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<LineVO> doDeal(FlowVO flow, NodeVO node, NodeInstVO nodeInst) {
        if (!(node instanceof ScriptNodeVO scriptNode)) throw new RuntimeException("节点类型不正确！");
        if (Tool.isBlank(scriptNode.getScriptId())) throw new RuntimeException("脚本名称不能为空！");

        Object result = GroovyService.runById(scriptNode.getScriptId(), nodeInst.getInput());
        if (result instanceof Map<?, ?> resultMap) {
            nodeInst.setOutput((Map<String, Object>) resultMap);
        }

        return flow.getLines()
                .stream()
                .filter(line -> line.getSource().equals(node.getId()))
                .collect(Collectors.toList());
    }
}
